package com.meida.module.bus.provider.service.impl;

import com.meida.common.base.entity.EntityMap;
import com.meida.common.base.utils.FlymeUtils;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.common.mybatis.query.CriteriaUpdate;
import com.meida.common.security.OpenHelper;
import com.meida.common.utils.ApiAssert;
import com.meida.common.utils.Base64;
import com.meida.common.utils.DateUtils;
import com.meida.common.utils.RedisUtils;
import com.meida.module.bbs.client.entity.BbsContent;
import com.meida.module.bbs.provider.service.BbsContentService;
import com.meida.module.bus.client.entity.BusScholartyrant;
import com.meida.module.bus.client.enums.AnswerStateEnum;
import com.meida.module.bus.client.enums.BalanceLogTypeEnum;
import com.meida.module.bus.provider.service.*;
import com.meida.module.bus.provider.utils.ImageSyntheticUtil;
import com.meida.module.bus.provider.utils.MyDateUtils;
import com.meida.module.pay.client.entity.PayBalance;
import com.meida.module.pay.provider.service.PayBalanceLogService;
import com.meida.module.pay.provider.service.PayBalanceService;
import com.meida.module.system.client.entity.SysDictData;
import com.meida.module.user.client.entity.AppEducational;
import com.meida.module.user.client.entity.AppSchool;
import com.meida.module.user.client.entity.AppUser;
import com.meida.module.user.client.entity.AppWorkhistory;
import com.meida.module.user.provider.service.AppEducationalService;
import com.meida.module.user.provider.service.AppUserService;
import com.meida.module.user.provider.service.AppWorkhistoryService;
import com.meida.module.user.provider.service.SysSliderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.text.NumberFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class AppUserMineServiceImpl implements AppUserMineService {

    @Autowired
    private BusScholartyrantService busScholartyrantService;

    @Autowired
    private PayBalanceService payBalanceService;

    @Autowired
    private PayBalanceLogService payBalanceLogService;

    @Autowired
    private AppUserService appUserService;

    @Autowired
    private AppEducationalService appEducationalService;

    @Autowired
    private AppWorkhistoryService appWorkhistoryService;

    @Autowired
    private BusOrderService busOrderService;

    @Autowired
    private BusOrderAnswerService busOrderAnswerService;

    @Autowired
    private BusAfterserviceService busAfterserviceService;

    @Autowired
    private BusSubjectService busSubjectService;

    @Autowired
    private SysSliderService sysSliderService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private BbsContentService bbsContentService;

    @Override
    public ResultBody getMineIncomeInfo(Long userId) {
        ApiAssert.isNotEmpty("缺少userId", userId);
        EntityMap data = new EntityMap();
        Boolean isScholarTyrant = busScholartyrantService.isScholarTyrant(userId);
        data.put("isScholarTyrant", isScholarTyrant);
        EntityMap scholarTyrantInfo = busScholartyrantService.getScholartyrantInfo(userId);
        data.put("scholarTyrantInfo", scholarTyrantInfo);
        BigDecimal incomeAmount = busOrderService.sumUserCommission(userId);
        data.put("incomeAmount", incomeAmount);
        //todo 需要处理今日收入
        //服务器时间是UTC,数据库时间是UTC
        BigDecimal todayIncomeAmount = busOrderService.totalTodayCommission(userId, DateUtils.formatDate());
        data.put("todayIncomeAmount", todayIncomeAmount);
        //todo 需要处理数据统计,轮播图
        //已领取：接单总数量
        Long receiveOrderNum = busOrderService.totalReceiveOrderNum(userId);
        data.put("receiveOrderNum", receiveOrderNum);
        //已上线：接单提交审核通过的订单数量
        Long orderAnswerPassNum = busOrderAnswerService.countNumByAnswerUserId(userId, AnswerStateEnum.checkPass.getValue());
        data.put("orderAnswerPassNum", orderAnswerPassNum);
        //被投诉：售后订单数量
        Integer afterServiceOrderNum = busAfterserviceService.totalAfterServiceOrderNum(userId);
        data.put("afterServiceOrderNum", afterServiceOrderNum);
        ///提交答案的次数
        Integer orderAnswerNum = busOrderAnswerService.countNumByAnswerUserId(userId);
        //审核通过率
        data.put("orderAnswerProportion", "0%");
        NumberFormat numberFormat = NumberFormat.getInstance();
        // 设置精确到小数点后2位
        numberFormat.setMaximumFractionDigits(2);
        if (orderAnswerNum > 0) {
            String result = numberFormat.format((float) orderAnswerPassNum / (float) orderAnswerNum * 100);
            data.put("orderAnswerProportion", result + "%");
        }
        //全部成单率
        data.put("finshOrderProportion", "0%");
        //放弃率
        data.put("giveUpOrderProportion", "0%");
        if (receiveOrderNum > 0) {
            Long num = orderAnswerPassNum - afterServiceOrderNum;
            String result = numberFormat.format((float) num / (float) receiveOrderNum * 100);
            data.put("finshOrderProportion", result + "%");
            String afterServiceOrder = numberFormat.format((float) afterServiceOrderNum / (float) receiveOrderNum * 100);
            data.put("giveUpOrderProportion", afterServiceOrder + "%");
        }
        List<EntityMap> sliderList = sysSliderService.listBySliderType(8);
        data.put("sliderList", sliderList);
        //解答中
        Long answerIngNum = busOrderService.countAnswerIngNum(userId);
        data.put("answerIngNum", answerIngNum);
        //审核中
        Long waitCheckNum = busOrderAnswerService.countNumByAnswerUserId(userId, AnswerStateEnum.checkIng.getValue());
        data.put("waitCheckNum", waitCheckNum);
        return ResultBody.ok(data);
    }

    @Override
    public ResultBody getUserScholartyrant(Long userId) {
        ApiAssert.isNotEmpty("缺少userId", userId);
        EntityMap data = new EntityMap();
        Integer scholarTyrantState = busScholartyrantService.getScholarTyrantState(userId);
        data.put("scholarTyrantState", scholarTyrantState);
        CriteriaQuery cq = new CriteriaQuery(AppUser.class);
        cq.select(AppUser.class, "userName", "email", "schoolId");
        cq.select(BusScholartyrant.class, "subjectInfo", "selfIntroduction");
        cq.eq(AppUser.class, "userId", userId);
        cq.createJoin(BusScholartyrant.class).setMainField("userId").setJoinField("scholartyrantId");
        EntityMap scholarTyrantIno = appUserService.findOne(cq);
        String email = scholarTyrantIno.get("email");
        ApiAssert.isNotEmpty("请先进行学校邮箱认证", email);
        if (FlymeUtils.isNotEmpty(scholarTyrantIno)) {
            String subjectInfo = scholarTyrantIno.get("subjectInfo");
            List<String> subjectTitles = busSubjectService.selectSubjectTitles(subjectInfo);
            scholarTyrantIno.put("subjectTitles", subjectTitles);
        }
        data.put("scholarTyrantIno", scholarTyrantIno);
        List<EntityMap> appEducationalList = appEducationalService.listByUserId(userId, q -> {
            q.select(AppEducational.class, "educationalId", "schoolId", "educationId", "major", "educationDate");
            q.select(SysDictData.class, "dicDataTitle");
            q.select(AppSchool.class, "schoolName", "schoolLogo");
            q.createJoin(AppSchool.class).setMainField("schoolId").setJoinField("schoolId");
            q.createJoin(SysDictData.class).setMainField("educationId").setJoinField("dictDataId");
        });
        data.put("educationalList", appEducationalList);
        List<EntityMap> workHistoryList = appWorkhistoryService.listByUserId(userId, workHistoryCq -> {
            workHistoryCq.select(AppWorkhistory.class, "workhistoryId", "positionName", "companyAddress", "workingDate");
        });
        data.put("workHistoryList", workHistoryList);
        return ResultBody.ok(data);
    }

    @Override
    public ResultBody getUserMineInfo(Long userId) {
        ApiAssert.isNotEmpty("缺少userId", userId);
        CriteriaQuery cq = new CriteriaQuery(AppUser.class);
        cq.select(AppUser.class, "nickName", "avatar", "sex");
        cq.select(BusScholartyrant.class, "tags", "selfIntroduction");
        cq.eq(AppUser.class, "userId", userId);
        cq.createJoin(BusScholartyrant.class).setMainField("userId").setJoinField("scholartyrantId");
        EntityMap userInfo = appUserService.findOne(cq);
        return ResultBody.ok(userInfo);
    }

    @Override
    public ResultBody updateUserMineInfo(Map params) {
        Long userId = OpenHelper.getUserId();
        CriteriaUpdate userCu = new CriteriaUpdate(params, AppUser.class);
        AppUser appUser = (AppUser) userCu.getEntity(AppUser.class);
        appUser.setUserId(userId);
        appUserService.updateById(appUser);
        return ResultBody.ok("更新成功");
    }

    @Override
    public ResultBody getScholarTyrantMineInfo(Long userId) {
        ApiAssert.isNotEmpty("缺少userId", userId);
        CriteriaQuery cq = new CriteriaQuery(AppUser.class);
        cq.select(AppUser.class, "nickName", "avatar", "sex", "birthday", "personProfile", "frontCoverImage");
        cq.select(BusScholartyrant.class, "tags");
        cq.select(AppSchool.class, "schoolName");
        cq.eq(AppUser.class, "userId", userId);
        cq.createJoin(AppSchool.class).setMainField("schoolId").setJoinField("schoolId");
        cq.createJoin(BusScholartyrant.class).setMainField("userId").setJoinField("scholartyrantId");
        EntityMap userInfo = appUserService.findOne(cq);
        return ResultBody.ok(userInfo);
    }

    @Override
    public ResultBody updateScholarTyrantMineInfo(Map params) {
        Long userId = OpenHelper.getUserId();
        String tags = (String) params.get("tags");
        //两个实体类字段重了
        params.remove("tags");
        CriteriaUpdate userCu = new CriteriaUpdate(params, AppUser.class);
        AppUser appUser = (AppUser) userCu.getEntity(AppUser.class);
        appUser.setUserId(userId);
        appUserService.updateById(appUser);
        BusScholartyrant busScholartyrant = (BusScholartyrant) userCu.getEntity(BusScholartyrant.class);
        busScholartyrant.setScholartyrantId(userId);
        busScholartyrant.setTags(tags);
        busScholartyrantService.updateById(busScholartyrant);
        return ResultBody.ok("更新成功");
    }

    @Override
    public ResultBody getIncomeCenter(Long userId) {
        EntityMap data = new EntityMap();
        PayBalance payBalance = payBalanceService.addUserBalance(userId);
        BigDecimal balanceAmount = payBalance.getAmount();
        EntityMap configMap = redisUtils.getConfigMap("CASHOUT_CONFIG");
        data.put("balanceAmount", balanceAmount);
        data.put("aliPayAccount", payBalance.getAliPayAccount());
        data.put("wxOpenId", payBalance.getWxOpenId());
        data.putAll(configMap);
        return ResultBody.ok(data);
    }

    @Override
    public ResultBody getShareImage(Long userId) {
        String base64 = "";
        try {
            AppUser appUser = appUserService.getById(userId);
            String avatar = appUser.getAvatar();
            String shareCode = appUser.getShareCode();
            String userNo = appUser.getUserNo();
            EntityMap imageConfig = redisUtils.getConfigMap("IMAGE_CONFIG");
            String shareImage = imageConfig.get("shareImage");
            //初始化画布
            BufferedImage canvas = ImageSyntheticUtil.drawInitByNetworkPath(shareImage, 750, 1174);
            //头像
            BufferedImage avatarCanvas = ImageIO.read(new URL(avatar));
            avatarCanvas = ImageSyntheticUtil.changeSize(avatarCanvas, 142, 142);
            //转成圆形
            avatarCanvas = ImageSyntheticUtil.convertCircular(avatarCanvas);
            Integer canvasWidth = Integer.valueOf(new BigDecimal(canvas.getWidth()).setScale(0, BigDecimal.ROUND_HALF_UP).toString());
            Integer avatarWidth = avatarCanvas.getWidth();
            BufferedImage bufferedImage = ImageSyntheticUtil.drawExtraImage(canvas, avatarCanvas, (canvasWidth - avatarWidth) / 2, 71);
            bufferedImage = ImageSyntheticUtil.drawWords(bufferedImage, new Color(245, 245, 245).getRGB(), "留同学" + userNo, 249, 10, 5, "微软雅黑", 28);
            bufferedImage = ImageSyntheticUtil.drawWords(bufferedImage, new Color(245, 245, 245).getRGB(), "我的邀请码", 328, 10, 5, "微软雅黑", 38);
            bufferedImage = ImageSyntheticUtil.drawWords(bufferedImage, Color.white.getRGB(), shareCode, 420, 10, 5, "微软雅黑", 60);
            //输出流
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "jpg", stream);
            base64 = Base64.encode(stream.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultBody.ok(base64);
    }

    @Override
    public ResultBody getShareContentImage(Long contentId) {
        String base64 = "";
        try {
            if (FlymeUtils.isEmpty(contentId)) {
                return ResultBody.failed("缺少contentId");
            }
            BbsContent bbsContent = bbsContentService.getById(contentId);
            if (FlymeUtils.isEmpty(bbsContent)) {
                return ResultBody.failed("缺少圈子信息");
            }
            Long userId = bbsContent.getUserId();
            String title = bbsContent.getTitle();
            AppUser appUser = appUserService.getById(userId);
            String avatar = appUser.getAvatar();
            String nickName = appUser.getNickName();
            EntityMap imageConfig = redisUtils.getConfigMap("IMAGE_CONFIG");
            String liuxuequanImage = imageConfig.get("liuxuequanImage");
            //初始化画布
            BufferedImage canvas = ImageSyntheticUtil.drawInitByNetworkPath(liuxuequanImage, 750, 1334);
            //画封面图
            String coverImage = bbsContent.getCoverImage();
            BufferedImage coverImageCanvas = ImageIO.read(new URL(coverImage));
            coverImageCanvas = ImageSyntheticUtil.changeSize(coverImageCanvas, 698, 840);
            Integer canvasWidth = Integer.valueOf(new BigDecimal(canvas.getWidth()).setScale(0, BigDecimal.ROUND_HALF_UP).toString());
            Integer coverImageCanvasWidth = coverImageCanvas.getWidth();
            BufferedImage bufferedImage = ImageSyntheticUtil.drawExtraImage(canvas, coverImageCanvas, (canvasWidth - coverImageCanvasWidth) / 2, 26);
            //画头像
            BufferedImage avatarCanvas = ImageIO.read(new URL(avatar));
            avatarCanvas = ImageSyntheticUtil.changeSize(avatarCanvas, 124, 122);
            //转成圆形
            avatarCanvas = ImageSyntheticUtil.convertCircular(avatarCanvas);
            bufferedImage = ImageSyntheticUtil.drawExtraImage(bufferedImage, avatarCanvas, 28, 805);
            //昵称
            bufferedImage = ImageSyntheticUtil.drawWords(bufferedImage, Color.black.getRGB(), nickName, 169, 910, 10, 5, "AppleColorEmoji", 32);
            //留学圈内容标题 超过28个字需要换行
            int length = title.length();
            if (length < 25) {
                bufferedImage = ImageSyntheticUtil.drawWords(bufferedImage, Color.darkGray.getRGB(), title, 26, 970, 10, 5, "AppleColorEmoji", 28);
            } else {
                String title1 = title.substring(0, 25);
                String title2 = title.substring(25, title.length());
                if (length > 56) {
                    title2 = title.substring(25, 48) + "......";
                }
                bufferedImage = ImageSyntheticUtil.drawWords(bufferedImage, Color.darkGray.getRGB(), title1, 26, 970, 10, 5, "AppleColorEmoji", 28);
                bufferedImage = ImageSyntheticUtil.drawWords(bufferedImage, Color.darkGray.getRGB(), title2, 26, 1010, 10, 5, "AppleColorEmoji", 28);
            }
            //输出流
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "jpg", stream);
            base64 = Base64.encode(stream.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultBody.ok(base64);
    }
}
